var net = require('net');
var config = require("../config/config");
//var serialport = require('./serialport');
var moment  = require('moment');
var db = require('./db.js');
var util = require('./util');

var socketArray = [];
var lastString = "";
var parseOneSocketData = function (data) {
    var res = {};
    var dataArray = data.split(",");
    if(dataArray.length == 3){
        if(dataArray[0] == "$BDMSG"){
            res.receiver = dataArray[1];
            res.content = dataArray[2];
            // res.content = dataArray[2].split("*")[0];
            res.time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
            res.state = "0";

            //存储数据库
            db.downMessage.create(res).then(function(msg){
                global.downMsg = msg.dataValues;
                console.log(global.downMsg);
                //确保数据库已经插入后再向串口发送数据;
                var dataSend = util.combineA4Msg(res.receiver, res.content);
                console.log(dataSend);
                //串口传输
                global.serialport.write(dataSend);
            });
        }
    }
}

var server = net.createServer();
    server.on('connection', function (socket) {
    socketArray.push(socket);
    socket.setKeepAlive(true);
    socket.on('close', function (e) {
        socket.end();
    });
    socket.on('error', function (e) {

    });
    socket.on('data', function (data){
        var dataStr = lastString+data.toString();
        //如果有大量数据则会组包
        var allDataArray = dataStr.split("*");

        for(var i = 0; i < allDataArray.length - 1; i++){
            parseOneSocketData(allDataArray[i]);
        }
        lastString = allDataArray[allDataArray.length-1];
        console.log("上一个剩余："+lastString);
    });
});

server.listen(config.socket_port, config.socket_ip, function () {
    console.log('start listening port '+ config.socket_port + ' on ' + config.socket_ip);
});

module.exports = {
    socketArray: socketArray,
};
